//
//  LHCustomTabBar.swift
//  sina_weibo
//
//  Created by 刘刘海强 on 16/5/11.
//  Copyright © 2016年 chuanzhi. All rights reserved.
//

import UIKit

class LHCustomTabBar: UITabBar {
    
    //创建回调的闭包
    var callBackClosure: (()->())?

    //通过懒加载创建自定义控件
    private lazy var composeButton: UIButton = {
        
        let btn = UIButton()
        
        //添加点击事件
        btn.addTarget(self, action: "composeButtonClik", forControlEvents: .TouchUpInside)
        
        //设置背景图片
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Selected)
        
        //设置图片
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Selected)
        
        btn.sizeToFit()
        
        return btn
        
    }()
    
    
    private func setupUI() {
        addSubview(composeButton)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        composeButton.center.x = frame.size.width * 0.5
        composeButton.center.y = frame.size.height * 0.5
        
        let itemWidth = frame.size.width / 5
        var index = 0
        
        //遍历子视图
        for childView in subviews {
            
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                childView.frame.size.width = itemWidth
                childView.frame.origin.x = CGFloat(index) * itemWidth
                index++
            }
            
            if index==2 {
                index++
            }
        }
    }
    
    
    @objc private func composeButtonClik() {
        callBackClosure?()
    }
    
}
